#include "GrayValueMeasurementResultWidget.h"
#include "ui_GrayValueMeasurementResultWidget.h"
#include <QtMath>
#include <QDebug>
#include <QGridLayout>
#include <QLabel>
#include <QPainter>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFileDialog>


GrayValueMeasurementResultWidget::GrayValueMeasurementResultWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GrayValueMeasurementResultWidget),
    m_series(new QLineSeries()),
    m_chart(new QChart()),
    m_axisX(new QValueAxis()),
    m_axisY(new QValueAxis()),
    m_currentDirection(HORIZONTAL),
    m_currentMeasurementType(""),
    m_chartContextMenu(new QMenu(this)),
    m_saveImageAction(new QAction("保存图像", this))
{
    ui->setupUi(this);

    // 设置数据系列样式，增强折线图效果
    QPen seriesPen(Qt::blue);
    seriesPen.setWidth(2); // 设置线条宽度
    seriesPen.setStyle(Qt::SolidLine); // 实线
    m_series->setPen(seriesPen);
    m_series->setPointsVisible(false); // 不显示数据点，保持折线图简洁
    
    // 设置轴 - 隐藏标题
    m_axisX->setTitleText(""); // 隐藏X轴标题
    m_axisY->setTitleText(""); // 隐藏Y轴标题
    
    // 添加轴到图表
    m_chart->addAxis(m_axisX, Qt::AlignBottom);
    m_chart->addAxis(m_axisY, Qt::AlignLeft);
    m_chart->addSeries(m_series);
    m_series->attachAxis(m_axisX);
    m_series->attachAxis(m_axisY);
    
    // 隐藏图表标题和图例
    m_chart->setTitle(""); // 隐藏图表标题
    m_chart->legend()->hide(); // 隐藏图例
    
    // 初始化轴范围设置
    m_axisX->setRange(0, 255); // X轴固定为0-255的灰度值范围
    m_axisY->setRange(0, 1);   // Y轴初始范围
    
    // 设置坐标轴刻度步长为整数，并确保标签显示为整数
    m_axisX->setTickInterval(1);
    m_axisY->setTickInterval(1);
    // 强制标签格式为整数
    m_axisX->setLabelFormat("%.0f");
    m_axisY->setLabelFormat("%.0f");
    
    // 将图表设置到UI的chartView中
    ui->chartView->setChart(m_chart);
    ui->chartView->setRenderHint(QPainter::Antialiasing);
    
    // 启用鼠标悬停提示
    ui->chartView->setMouseTracking(true);
    m_chart->setAcceptHoverEvents(true);
    
    // 配置tooltip显示坐标信息
    ui->chartView->setToolTip(QStringLiteral("%1, %2"));
    
    // 为图表视图添加鼠标移动事件处理，用于显示坐标提示
    connect(m_series, &QLineSeries::hovered, this, [this](const QPointF &point, bool state) {
        if (state) {
            // 将坐标值格式化为整数显示
            QString tooltip = QString("灰度值: %1, 数量: %2").arg(point.x(), 0, 'f', 0).arg(point.y(), 0, 'f', 0);
            ui->chartView->setToolTip(tooltip);
        } else {
            ui->chartView->setToolTip("");
        }
    });
    
    // 设置chartView的尺寸策略，确保它能够适当拉伸
    ui->chartView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    
    // 设置图表边距为0，减少空白区域
    m_chart->setMargins(QMargins(0, 0, 0, 0));
    // 确保主布局正确设置
    if (layout()) {
        // 设置布局为扩展策略
        layout()->setSizeConstraint(QLayout::SetDefaultConstraint);
        layout()->setContentsMargins(10, 10, 10, 10);
    }
    
    // 默认隐藏方向选择widget
    ui->directionSelectionWidget->hide();
    
    // 默认选择横向
    ui->horizontalDirectionRadio->setChecked(true);
    
    // 连接单选框信号
    connect(ui->horizontalDirectionRadio, &QRadioButton::toggled, this, [this](bool checked) {
        if (checked && m_currentMeasurementType == "RectangleRegion") {
            m_currentDirection = HORIZONTAL;
            // 重新计算并更新图表
            updateGrayHistogramForDirection();
        }
    });
    
    connect(ui->verticalDirectionRadio, &QRadioButton::toggled, this, [this](bool checked) {
        if (checked && m_currentMeasurementType == "RectangleRegion") {
            m_currentDirection = VERTICAL;
            // 重新计算并更新图表
            updateGrayHistogramForDirection();
        }
    });
    
    // 设置右键菜单
    m_chartContextMenu->addAction(m_saveImageAction);
    ui->chartView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->chartView, &QChartView::customContextMenuRequested, this, [this](const QPoint &pos) {
        m_chartContextMenu->exec(ui->chartView->mapToGlobal(pos));
    });
    
    // 连接保存图像信号
    connect(m_saveImageAction, &QAction::triggered, this, &GrayValueMeasurementResultWidget::saveChartImage);

}

GrayValueMeasurementResultWidget::~GrayValueMeasurementResultWidget()
{
    delete m_series;
    delete m_axisX;
    delete m_axisY;
    delete m_chart;
    delete m_saveImageAction;
    delete m_chartContextMenu;
    delete ui;
}

void GrayValueMeasurementResultWidget::updateGrayValueResult(const QVariantMap &result)
{
    // 保存当前结果
    m_lastResult = result;
    
    // 检查结果是否包含必要的数据
    if (!result.contains("gray_values") && !result.contains("error")) {
        qWarning() << "Invalid gray value measurement result: missing required fields";
        return;
    }

    // 检查是否有错误信息
    if (result.contains("error")) {
        qWarning() << "Gray value measurement error:" << result.value("error").toString();
        return;
    }
    
    // 获取测量类型
    m_currentMeasurementType = result.value("measurement_type").toString();
    
    // 根据测量类型决定是否显示方向选择widget
    if (m_currentMeasurementType == "RectangleRegion") {
        ui->directionSelectionWidget->show();
    } else {
        ui->directionSelectionWidget->hide();
    }

    // 提取灰度值列表
    QList<int> grayValues = result.value("gray_values").value<QList<int>>();
    
    if (m_currentMeasurementType == "RectangleRegion") {
        // 矩形测量的特殊处理
        int width = result.value("width", 0).toInt();
        int height = result.value("height", 0).toInt();
        
        // 计算按方向的平均值
        m_directionAverages.clear();
        
        if (width > 0 && height > 0 && grayValues.size() == width * height) {
            if (m_currentDirection == HORIZONTAL) {
                // 横向计算：按行求平均
                for (int y = 0; y < height; ++y) {
                    double sum = 0;
                    for (int x = 0; x < width; ++x) {
                        int index = y * width + x;
                        if (index < grayValues.size()) {
                            sum += grayValues[index];
                        }
                    }
                    m_directionAverages[y] = sum / width;
                }
            } else {
                // 纵向计算：按列求平均
                for (int x = 0; x < width; ++x) {
                    double sum = 0;
                    for (int y = 0; y < height; ++y) {
                        int index = y * width + x;
                        if (index < grayValues.size()) {
                            sum += grayValues[index];
                        }
                    }
                    m_directionAverages[x] = sum / height;
                }
            }
        }
        
        // 更新方向相关的直方图
        updateGrayHistogramForDirection();
    } else {
        // 非矩形测量，使用原来的方式更新直方图
        updateGrayHistogram(grayValues);
    }
    
    // 计算统计信息（使用所有像素）
    QVariantMap statistics = calculateGrayStatistics(grayValues);
    
    // 更新统计信息标签
    if (!statistics.isEmpty()) {
        ui->avgGrayValueLabel->setText(QString::number(statistics.value("average").toDouble(), 'f', 1));
        ui->stdDevValueLabel->setText(QString::number(statistics.value("stdDev").toDouble(), 'f', 1));
    }
    
    // 显示窗口
    this->setVisible(true);
}

void GrayValueMeasurementResultWidget::updateGrayHistogramForDirection()
{
    // 清空现有数据
    m_series->clear();
    
    if (m_directionAverages.isEmpty()) {
        return;
    }
    
    // 正确实现灰度分布图：X轴是0-255的灰度值，Y轴是对应灰度值的像素数量
    QMap<int, int> histogram;
    int maxCount = 0;
    int minGray = 255;
    int maxGray = 0;
    
    // 统计每个灰度值出现的次数，并记录最小和最大灰度值
    foreach (double gray, m_directionAverages.values()) {
        int grayInt = static_cast<int>(gray); // 将double转为int
        if (grayInt >= 0 && grayInt <= 255) {
            histogram[grayInt]++;
            maxCount = qMax(maxCount, histogram[grayInt]);
            minGray = qMin(minGray, grayInt);
            maxGray = qMax(maxGray, grayInt);
        }
    }
    
    // 添加数据到图表 - 只添加实际存在的灰度值点
    QMapIterator<int, int> i(histogram);
    while (i.hasNext()) {
        i.next();
        // 确保添加的是整数值
        m_series->append(static_cast<qreal>(i.key()), static_cast<qreal>(i.value()));
    }
    
    // 更新轴范围 - X轴调整为最小灰度到最大灰度，保留一些边距
    int xMargin = 5; // 边距大小
    int xMin = qMax(0, minGray - xMargin);
    int xMax = qMin(255, maxGray + xMargin);
    m_axisX->setRange(xMin, xMax);
    
    // Y轴范围设置为0到最大像素数量的1.1倍，确保能看到所有数据
    if (maxCount > 0) {
        m_axisY->setRange(0, maxCount * 1.1);
    } else {
        m_axisY->setRange(0, 1);
    }
    
    // 确保标题保持隐藏
    m_axisX->setTitleText("");
    m_axisY->setTitleText("");
    
    // 确保坐标轴刻度步长为整数，并确保标签显示为整数
    m_axisX->setTickInterval(1);
    m_axisY->setTickInterval(1);
    // 强制标签格式为整数
    m_axisX->setLabelFormat("%.0f");
    m_axisY->setLabelFormat("%.0f");
    
    // 更新最小和最大灰度值到界面
    ui->minGrayValueLabel->setText(QString::number(minGray));
    ui->maxGrayValueLabel->setText(QString::number(maxGray));
    
    // 强制更新图表
    m_chart->update();
    ui->chartView->updateGeometry();
    ui->chartView->repaint();
}

QVariantMap GrayValueMeasurementResultWidget::calculateGrayStatistics(const QList<int> &grayValues)
{
    QVariantMap stats;
    
    if (grayValues.isEmpty()) {
        return stats;
    }
    
    // 计算平均值
    qreal sum = 0;
    int minVal = 255;
    int maxVal = 0;
    
    foreach (int gray, grayValues) {
        sum += gray;
        minVal = qMin(minVal, gray);
        maxVal = qMax(maxVal, gray);
    }
    
    qreal average = sum / grayValues.size();
    
    // 计算标准差
    qreal variance = 0;
    foreach (int gray, grayValues) {
        variance += qPow(gray - average, 2);
    }
    qreal stdDev = qSqrt(variance / grayValues.size());
    
    // 存储统计信息
    stats.insert("average", average);
    stats.insert("stdDev", stdDev);
    stats.insert("min", minVal);
    stats.insert("max", maxVal);
    
    return stats;
}

void GrayValueMeasurementResultWidget::updateGrayHistogram(const QList<int> &grayValues)
{
    if (grayValues.isEmpty()) {
        return;
    }
    
    // 清空现有数据
    m_series->clear();
    
    // 正确实现灰度分布图：X轴是0-255的灰度值，Y轴是对应灰度值的像素数量
    QMap<int, int> histogram;
    int maxCount = 0;
    int minGray = 255;
    int maxGray = 0;
    
    // 统计每个灰度值出现的次数，并记录最小和最大灰度值
    foreach (int gray, grayValues) {
        if (gray >= 0 && gray <= 255) {
            histogram[gray]++;
            maxCount = qMax(maxCount, histogram[gray]);
            minGray = qMin(minGray, gray);
            maxGray = qMax(maxGray, gray);
        }
    }
    
    // 添加数据到图表 - 只添加实际存在的灰度值点
    QMapIterator<int, int> i(histogram);
    while (i.hasNext()) {
        i.next();
        // 确保添加的是整数值
        m_series->append(static_cast<qreal>(i.key()), static_cast<qreal>(i.value()));
    }
    
    // 更新轴范围 - X轴调整为最小灰度到最大灰度，保留一些边距
    int xMargin = 5; // 边距大小
    int xMin = qMax(0, minGray - xMargin);
    int xMax = qMin(255, maxGray + xMargin);
    m_axisX->setRange(xMin, xMax);
    
    // Y轴范围设置为0到最大像素数量的1.1倍，确保能看到所有数据
    if (maxCount > 0) {
        m_axisY->setRange(0, maxCount * 1.1);
    } else {
        m_axisY->setRange(0, 1);
    }
    
    // 确保标题保持隐藏
    m_axisX->setTitleText("");
    m_axisY->setTitleText("");
    
    // 确保坐标轴刻度步长为整数，并确保标签显示为整数
    m_axisX->setTickInterval(1);
    m_axisY->setTickInterval(1);
    // 强制标签格式为整数
    m_axisX->setLabelFormat("%.0f");
    m_axisY->setLabelFormat("%.0f");
    
    // 更新最小和最大灰度值到界面
    ui->minGrayValueLabel->setText(QString::number(minGray));
    ui->maxGrayValueLabel->setText(QString::number(maxGray));
    
    // 强制更新图表
    m_chart->update();
    ui->chartView->updateGeometry();
    ui->chartView->repaint();
}

void GrayValueMeasurementResultWidget::saveChartImage()
{
    // 打开文件保存对话框
    QString fileName = QFileDialog::getSaveFileName(this, "保存图表图像", QDir::homePath(), 
                                                   "PNG图像 (*.png);;JPEG图像 (*.jpg *.jpeg);;BMP图像 (*.bmp)");
    
    if (fileName.isEmpty()) {
        return; // 用户取消了保存
    }
    
    // 创建QPixmap用于绘制图表
    QPixmap pixmap(ui->chartView->size());
    QPainter painter(&pixmap);
    
    // 清空背景
    painter.fillRect(pixmap.rect(), Qt::white);
    
    // 绘制图表
    ui->chartView->render(&painter);
    
    // 保存图像
    if (pixmap.save(fileName)) {
        qInfo() << "图表图像保存成功:" << fileName;
    } else {
        qWarning() << "图表图像保存失败:" << fileName;
    }
}

void GrayValueMeasurementResultWidget::clearResults()
{
    // 清空图表数据
    m_series->clear();
    
    // 重置统计信息标签
    ui->avgGrayValueLabel->setText("0");
    ui->stdDevValueLabel->setText("0");
    ui->minGrayValueLabel->setText("0");
    ui->maxGrayValueLabel->setText("0");
    
    // 隐藏窗口
    this->setVisible(false);
}
